using System.Collections.Generic;
using System.Linq;
using Data;
using Model.Entities;
using Nethouse.Lib.Mvp;

namespace Business.EditOrderUC
{
    public class SelectOrderPresenter : Presenter<ISelectOrderView>
    {
        private readonly IRepository<Company> companyRepository;
        private readonly IRepository<Order> orderRepository;

        public SelectOrderPresenter(IRepository<Company> companyRepository, IRepository<Order> orderRepository)
        {
            this.companyRepository = companyRepository;
            this.orderRepository = orderRepository;
        }

        protected override void ViewCreated()
        {
            View.CompanyList = companyRepository.All().ToList();
            View.OrderList = new List<Order>();
        }

        protected override void ViewLoaded()
        {
            View.CompanyChanged += ViewOnCompanyChanged;
            View.OrderChanged += ViewOnOrderChanged;

        }

        private void ViewOnCompanyChanged()
        {
            if (View.CurrentCompany > 0)
            {
                Company currentCompany = companyRepository.GetById(View.CurrentCompany);
                View.OrderList = currentCompany.OrderList;
            }
            else
            {
                View.OrderList = new List<Order>();
            }

            ViewOnOrderChanged();
        }

        private void ViewOnOrderChanged()
        {
            OrderSelected orderSelected = new OrderSelected() {OrderId = View.CurrentOrder};
            EventBus.Publish(orderSelected);
        }
    }
}
